package com.yuelao.currentlimit;

import com.google.common.util.concurrent.RateLimiter;
import org.joda.time.DateTime;

import java.util.concurrent.TimeUnit;

/**
 * 限流实现
 *
 * @author fengliye
 * @version v1.0
 * @date 2019/03/20 14:44
 * @modify detail
 * 版本       修改人        修改时间      修改内容描述
 * ---------------------------------------------
 * <p>
 * ---------------------------------------------
 */
public class CurrentLimit implements Runnable {
    private RateLimiter rateLimiter;
    private boolean runing = true;

    public CurrentLimit(RateLimiter rateLimiter) {
        this.rateLimiter = rateLimiter;
    }

    @Override
    public void run() {
        while (runing) {
            System.out.println(Thread.currentThread().getName() + "#####"+ rateLimiter.acquire()); // or rateLimiter.tryAcquire()
            //rateLimiter.tryAcquire();
            // getData();
        }
    }

    // 模拟调用合作伙伴API接口
    private void getData() {
        System.out.println(DateTime.now().toString("yyyy-MM-dd HH:mm:ss") + ", " + Thread.currentThread().getName() + " runing!");
        try {
            TimeUnit.MILLISECONDS.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
